package top.majuan.study.study.servlet.news;

import top.majuan.study.study.dao.TbNewsDAO;
import top.majuan.study.study.entity.Result;
import top.majuan.study.study.entity.TbNews;
import top.majuan.study.study.util.JsonUtils;
import top.majuan.study.study.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "newsmodify", urlPatterns = "/news/modify.action")
public class ModifyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        text/plain
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
//       获取请求中的新闻数据
        Integer id = Integer.parseInt(req.getParameter("id"));
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        String source = req.getParameter("source");
//        基础数据校验
        if (StringUtil.isBlank(title)) {
            Result<String> result = Result.fail("标题不能为空", null);
            writer.println(JsonUtils.stringify(result));
            return;
        }
        if (StringUtil.isBlank(content)) {
            Result<String> result = Result.fail("内容不能为空", null);
            writer.println(JsonUtils.stringify(result));
            return;
        }
        if (StringUtil.isBlank(source)) {
            Result<String> result = Result.fail("来源不能为空", null);
            writer.println(JsonUtils.stringify(result));
            return;
        }

        TbNews news = new TbNews();
        news.setId(id);
        news.setTitle(title);
        news.setContent(content);
        news.setSource(source);
//        修改到数据库
        try {
            int i = TbNewsDAO.update(news);
            if (i == 1) {
                Result<String> result = Result.success("修改成功");
                writer.println(JsonUtils.stringify(result));
            } else {
                Result<String> result = Result.fail("修改失败", null);
                writer.println(JsonUtils.stringify(result));
            }

        } catch (Exception e) {
            e.printStackTrace();
            Result<String> result = Result.fail("修改发生错误", null);
            writer.println(JsonUtils.stringify(result));
        }

    }
}
